package com.cyh.ebptpubjar.common.ebptjasypt;

import com.ulisesbocchio.jasyptspringboot.EncryptablePropertyResolver;
import org.jasypt.encryption.pbe.PooledPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.SimpleStringPBEConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import java.util.Base64;

/**
 * @ClassName:   EbptEncryptablePropertyResolver
 * @Description:
 * @Author:      cyh
 * @CreateDate:  2022/1/12 21:12
 */
@Configuration
public class EbptEncryptablePropertyResolver implements EncryptablePropertyResolver {

    private final PooledPBEStringEncryptor encryptor;
    // 加密盐值
    private final String PASSWORD = "salt";
    @Autowired
    EbptEncryptablePropertyDetector encryptablePropertyDetector;

    public EbptEncryptablePropertyResolver() {
        this.encryptor = new PooledPBEStringEncryptor();
        SimpleStringPBEConfig config = new SimpleStringPBEConfig();
        config.setPasswordCharArray(PASSWORD.toCharArray());
        config.setAlgorithm("PBEWITHHMACSHA512ANDAES_256");
        config.setKeyObtentionIterations("1000");
        config.setPoolSize(1);
        config.setProviderName("SunJCE");
        config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
        config.setIvGeneratorClassName("org.jasypt.iv.RandomIvGenerator");
        config.setStringOutputType("base64");
        encryptor.setConfig(config);
    }

    @Override
    public String resolvePropertyValue(String value) {
        if (null != value && encryptablePropertyDetector.isEncrypted(value)) {
            //对配置文件加密值进行解密。加密方式可以自定义
            value = encryptablePropertyDetector.unwrapEncryptedValue(value);
//            //使用base64 解密 value带有前缀的值
//            byte[] decoded = Base64.getDecoder().decode(value);
//            String decodeStr = new String(decoded);
            String decodeStr = encryptor.decrypt(value);
            //String decodeStr = "ebptdb";
            return decodeStr;
        }
        return value;
    }
}
